import os
import re


def remove_unused_reference(latex_path, bib_path: str, output_bib_path: str):
    with open(bib_path, mode='r', encoding='utf-8') as f:
        bib_text = f.read()
    items = bib_text.strip().split('@')[1:]
    names = []
    for item in items:
        name = item.split(',')[0].split('{')[-1]
        names.append(name)

    latex_path_list = []
    for path in latex_path:
        if os.path.isdir(path):
            for name in os.listdir(path):
                if not name.endswith('.tex'):
                    continue
                latex_path_list.append(f'{path}/{name}')
        else:
            latex_path_list.append(path)

    latex_text_list = []
    for latex_path in latex_path_list:
        with open(latex_path, mode='r', encoding='utf-8') as f:
            latex_text_list.append(f.read())
    latex_text = '\n'.join(latex_text_list)
    removed_items = []
    for i in range(len(names)):
        name = names[i]
        item = items[i]
        find_result = re.findall(name, latex_text)
        if len(find_result) != 0:
            removed_items.append(item)
    print(f'total [{len(items)}] references, after deleting unused, leave [{len(removed_items)}]')
    result = '@'.join(removed_items)
    result = '@' + result
    with open(output_bib_path, mode='w', encoding='utf-8') as f:
        f.write(result)
    print(f'output bib at [{output_bib_path}]')
